package com.sky.controller.User;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    JwtProperties jwtProperties;

    /**
    * @Description:
    * @return  用户登录
    * @author 小陈
    * @Params:
    * @DateTime:
    */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        //1.接受参数：json
        log.info("用户登录：{}", userLoginDTO);

        //2.调用service层，微信登录
        User user = userService.checkLogin(userLoginDTO);

        //登录成功，颁发令牌
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>(); //创建载荷
        claims.put(JwtClaimsConstant.USER_ID, user.getId());


        String token = JwtUtil.createJWT(  //调用jjwt生成令牌
                jwtProperties.getUserSecretKey(), //kunkun
                jwtProperties.getUserTtl(), //720000
                claims);


        //3.封装结果数据
        return Result.success(UserLoginVO.builder()
                .token(token)
                .openid(user.getOpenid())
                .id(user.getId())
                .build());
    }
}
